<template style='height: 100%'>
  <div id='vmList'>
    <div>
      <div style='float: left;'>
        <el-button @click='cerateVm' type='primary' size='mini' icon='el-icon-plus'>{{ $t('Vm.add') }}</el-button>
        <el-button @click='importVM' type='primary' size='mini'>{{ $t('Vm.import') }}</el-button>
        <el-button @click='openDialog' type='danger' :disabled='deleteDisabled' size='mini'
                   icon='el-icon-delete' class='button-margin'>{{ $t('Vm.delete') }}
        </el-button>
        <el-dropdown @command="handleMoreOperationsCommand">
          <el-button size='mini'>
            {{$t('Vm.more')}}<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <!-- TODO:暂不支持组内分配回收 TEAM_ADMIN_ROLE -->
            <el-dropdown-item v-if="checkPermission(['SUPER_ADMIN_ROLE','BUSINESS_UNIT_ADMIN_ROLE','DOMAIN_ADMIN_ROLE'])"
                              command="deliver" :disabled="deliverBtnDisabled">{{$t('Vm.deliver')}}</el-dropdown-item>
            <el-dropdown-item v-if="checkPermission(['SUPER_ADMIN_ROLE','BUSINESS_UNIT_ADMIN_ROLE','DOMAIN_ADMIN_ROLE'])"
                              command="reclaim" :disabled="reclaimBtnDisabled">{{$t('Vm.reclaim')}}</el-dropdown-item>
            <!-- <el-dropdown-item v-if="checkPermission(['DOMAIN_ADMIN_ROLE','TEAM_ADMIN_ROLE'])"
                        command="multiChange" :disabled="multiConfigDisabled">{{$t('vmHost.multiChange')}}</el-dropdown-item> -->
            <el-dropdown-item v-if="checkPermission(['DOMAIN_ADMIN_ROLE','TEAM_ADMIN_ROLE'])"
                              command="multiRemove" :disabled="multiRemoveDisabled">{{$t('Vm.multiRemove')}}</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
    <div style='float: right;'>
      <el-select v-model='filters.searchType' style='width: 105px;' size='mini' @change='changeSearchType'>
        <el-option key='1' :label="$t('Vm.vmName')" value='1'></el-option>
        <el-option key='2' :label="$t('Vm.ip')" value='2'></el-option>
      </el-select>
      <el-input :placeholder="$t('Vm.placeholder')" v-model.trim='filters.name' clearable size='mini'
                style='width: auto;padding-left: 5px;' v-if='filters.searchType == 1'></el-input>
      <el-input :placeholder="$t('ip.placeholder')" v-model.trim='filters.ipAddress' clearable size='mini'
                style='width: auto;padding-left: 5px;' v-if='filters.searchType == 2'></el-input>
      <el-button @click='clickSearch()' type='primary' size='mini'>{{ $t('Vm.search') }}</el-button>
    </div>
    <div style='padding-top: 40px'>
      <table-contain :height.sync="table.maxHeight">
        <el-table :data='tableData' ref='multipleTable' border highlight-current-row slot="table"
                  @selection-change='handleSelectionChange' :height="table.maxHeight">
          <el-table-column type='selection' align='center' width='55'></el-table-column>
          <el-table-column prop='instanceName' :label="$t('vms.instanceName')" min-width='120'
                           show-overflow-tooltip></el-table-column>
          <el-table-column prop='stateName' :label="$t('vms.stateName')" min-width='50'
                           show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-html="getStateIcon(scope.row.state, scope.row.stateName)" style="text-align: center;"></div>
            </template>
          </el-table-column>
          <el-table-column prop='cloudPlatformName' :label="$t('vms.cloudPlatformName')"
                           width='120'></el-table-column>
          <el-table-column prop='instanceChargeTypeName' :label="$t('vms.instanceChargeTypeName')"
                           width='120'></el-table-column>
          <el-table-column prop='regionName' :label="$t('vms.regionName')" min-width='60'
                           show-overflow-tooltip></el-table-column>
          <el-table-column prop='zoneName' :label="$t('vms.zoneName')" min-width='60'
                           show-overflow-tooltip></el-table-column>
          <el-table-column prop='osName' :label="$t('vms.osName')" min-width='60'
                           show-overflow-tooltip></el-table-column>
<!--          <el-table-column prop='hostName' :label="$t('vms.hostname')" min-width='100'-->
<!--                           show-overflow-tooltip></el-table-column>-->
          <el-table-column prop='ip' :label="$t('vms.ip')" min-width='80' show-overflow-tooltip></el-table-column>
          <el-table-column prop='internetChargeTypeName' :label="$t('vms.internetChargeTypeName')"
                           width='120'></el-table-column>
          <el-table-column prop='internetMaxBandwidthOut' :label="$t('vms.internetMaxBandwidthOut')"
                           width='120'></el-table-column>
          <el-table-column prop='cpu' :label="$t('vms.cpu')" min-width='60' show-overflow-tooltip></el-table-column>
          <el-table-column :prop="'memory'" :label="$t('vms.memory')" :min-width="60" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.memory / 1024 }}
            </template>
          </el-table-column>
          <!-- 数据中心管理员和运营管理员可以对运营进行过滤，数据中心过滤所有，运营管理员过滤自己管理的运营中心 -->
          <el-table-column v-if="checkPermission(['SUPER_ADMIN_ROLE','BUSINESS_UNIT_ADMIN_ROLE'])"
                           prop="resourceUnitId" :label="$t('Vm.operationUnit')" min-width=100 show-overflow-tooltip
                           :filters="businessUnitFilterCondition" column-key="operationUnit" :formatter="formatterBusinessUnit"
                           :filter-multiple="false" filter-placement="bottom">
          </el-table-column>
          <!-- 部门管理员可以管理多个部门，可以对部门进行过滤，其他角色不提供过滤功能 -->
          <el-table-column v-if="checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])" prop="resourceDomainName" :label="$t('Vm.resourceDomain')"
                           min-width=90 show-overflow-tooltip></el-table-column>
          <el-table-column v-if="checkPermission(['DOMAIN_ADMIN_ROLE'])" prop="resourceDomainName" :label="$t('Vm.resourceDomain')"
                           min-width=90 column-key="domain" show-overflow-tooltip
                           :filters="domainFilterCondition" :filter-multiple="false" filter-placement="bottom"></el-table-column>
          <!-- 项目管理员（组管理员）可以管理多个项目，可以对项目进行过滤，其他角色不提供过滤功能 -->
          <el-table-column v-if="checkPermission(['BUSINESS_UNIT_ADMIN_ROLE','DOMAIN_ADMIN_ROLE','TEAM_MEMBER_ROLE'])"
                           prop="resourceGroupName" :label="$t('Vm.project')" min-width=100
                           show-overflow-tooltip></el-table-column>
          <el-table-column v-if="checkPermission(['TEAM_ADMIN_ROLE'])"
                           prop="resourceGroupName" :label="$t('Vm.project')" min-width=100  :filters="teamFilterCondition"
                           :filter-multiple="false" column-key="team" show-overflow-tooltip></el-table-column>
          <el-table-column :label="$t('vms.operation')" align='center' width='120'>
            <template slot-scope='scope'>
              <el-button size='mini' v-if='checkResourceState(scope.row.state,showdata.start)' type='text'
                         @click='startVm(scope.row)'>{{ $t('vms.start') }}
              </el-button>
              <el-button size='mini' v-if='checkResourceState(scope.row.state,showdata.stop)' type='text'
                         @click='stopVm(scope.row)'>{{ $t('vms.stop') }}
              </el-button>
              <el-button size='mini' v-if='checkResourceState(scope.row.state,showdata.restart)' type='text'
                         @click='restartVm(scope.row)'>{{ $t('vms.restart') }}
              </el-button>

              <el-button size='mini' v-if='checkResourceState(scope.row.state,showdata.restart)' type='text'
                         @click='showPassword(scope.row)'>{{ $t('vms.showPassword') }}
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination slot='footer' @size-change='handleSizeChange' @current-change='handleCurrentChange'
                       :current-page='currentPage' :page-sizes='[10,20,50,100]' :page-size='pageSize'
                       layout='total, sizes, prev, pager, next' :total='totalSize'>
        </el-pagination>
      </table-contain>
    </div>
    <el-dialog :visible.sync='dialogVisible' title='删除方式'>
      <el-form label-width='80px'>
        <el-form-item>
          <el-radio-group v-model='deleteType' style='margin-left: 20%;'>
            <el-radio v-for='option in options' :label='option.value' :key='option.value'>{{ option.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <span slot='footer' class='dialog-footer'>
        <el-button @click='dialogVisible = false'>取消</el-button>
        <el-button type='primary' @click='clickDelete' style='margin-left: 20px'>确定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="$t('deliverForm.title')" :visible.sync="deliverDialogVisible" @open="loadDeliverDestinationInfo"
      width="450px" :before-close="handleCloseDeliverDialog">
      <el-form ref="deliverForm" :model="deliverForm" :rules="deliverFormRules" label-width="100px">
        <el-form-item v-if="checkPermission(['SUPER_ADMIN_ROLE'])" :label="$t('deliverForm.businessUnit')" prop="businessUnitId">
          <el-select v-model="deliverForm.businessUnitId" :placeholder="$t('deliverForm.placeholder.businessUnit')" style="width: 300px">
            <el-option v-for="item in businessUnitList"
                       :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])" :label="$t('deliverForm.deliverLocation')" prop="domainTeamTreeValue">
          <a-tree-select v-model="deliverForm.domainTeamTreeValue" allowClear showSearch treeNodeFilterProp="title"
                         style="width: 300px" :treeData="businessUnitDomainTreeFormat"  :dropdownStyle="{ maxHeight: '400px', overflow: 'auto','z-index':30000 }"
                         :searchPlaceholder="$t('deliverForm.placeholder.domain')"/>
        </el-form-item>
        <el-form-item v-if="checkPermission(['DOMAIN_ADMIN_ROLE'])" :label="$t('deliverForm.deliverLocation')">
          <el-select v-model="deliverForm.teamId" :placeholder="$t('deliverForm.placeholder.choose')" style="width: 300px" >
            <el-option
              v-for="item in domainTeamList"
              :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])" :label="$t('deliverForm.deadline')" prop="deadline">
          <el-date-picker  v-model="deliverForm.deadline" type="date" clearable
                           :picker-options="deadlinePickerOptions"
                           :placeholder="$t('deliverForm.placeholder.deadline')"
                           style="width: 300px"></el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('deliverForm.description')">
          <el-input type="textarea" :rows="2" v-model="deliverForm.description" style="width: 300px" maxlength="100"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deliverVMs" size="mini">{{$t('confirm.ok')}}</el-button>
        <el-button @click="deliverDialogVisible = false" size="mini">{{$t('confirm.cancel')}}</el-button>
      </span>
    </el-dialog>


    <el-dialog
      :title="$t('deliverForm.showPassword')" :visible.sync="passwordDialogVisible" @open="loadDeliverDestinationInfo"
      width="450px"   @before-close="passwordDialogVisible = false">
      <span  class="dialog-footer">
         云服务器密码如下，请妥善保管<strong>{{password}}</strong>
      </span>

      <span slot="footer" class="dialog-footer">
        <el-button @click="passwordDialogVisible = false" size="mini">{{$t('confirm.cancel')}}</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<style lang='scss'>
@import '../../../assets/iconfont/iconfont.css';

//icon 图标旋转
@keyframes whirling {
  from{
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

#vmList {
  & .el-button + .el-button {
    margin-left: 0px;
  }
  .el-input--medium .el-input__inner {
    height: 32px;
  }
}

.vm-status-running {
  color: #21903A;
}

.vm-status-stopped {
  color: #F56954;
}

.vm-status-unknown {
  color: #55A3F5;
}

.vm-status-paused {
  color: #1781FA;
}

.vm-status-error {
  color: #CF3736;
}

.vm-status-in-progress {
  //  color: #FAAD14;
  color: #fa9700;
  display: inline-block;
  animation: whirling 1.5s linear infinite;
}

</style>
<script>
import model from '@/public/indexModel.js'
import local from './js/local'
import pubVmApi from '@/api/pubVmApi.js'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'
import messageApi from '@/api/messageApi'
import pubVmUtil from './js/pubVmUtil'
import checkPermission from '../../../utils/permission'
import businessUnitApi from '@/api/businessUnitApi'
import vdcApi from '@/api/vdcApi'
import domainApi from '../../../api/domainApi'

export default {
  mixins: [model],
  name: 'vmList',
  i18n: {
    messages: local
  },
  data() {
    return {
      deadlinePickerOptions: {
        disabledDate(time) {
          return time.getTime() + 3600 * 1000 * 24 < Date.now()// 到期时间选当天和以后的时间
        }
      },
      domainTeamList: [],
      businessUnitDomainTree: [],
      businessUnitDomainTreeFormat: [],
      businessUnitList: [],
      deliverFormRules: {
        businessUnitId: [{ required: true, message: this.$t('deliverForm.validate.not_empty'), trigger: 'change' }],
        domainTeamTreeValue: [{ required: true, message: this.$t('deliverForm.validate.not_empty'), trigger: 'change' }],
        deadline: []
      },
      deliverForm: {
        domainTeamTreeValue: '',
        businessUnitId: '',
        teamId: '',
        deadline: '',
        description: ''
      },
      deliverDialogVisible: false, // 分配的dialog
      passwordDialogVisible: false, // 展示密码的dialog
      password: '',
      deliverBtnDisabled: true,
      reclaimBtnDisabled: true,
      multiConfigDisabled: true,
      multiRemoveDisabled: true,
      showdata: {
        start: ['STOPPED'],
        restart: ['RUNNING'],
        stop: ['RUNNING']
      },
      deleteType: 'local',
      dialogVisible: false,
      options: [
        { label: '删除本地数据', value: 'local' },
        { label: '删除本地以及云数据', value: 'cloud' }
      ],
      // VM查询时的过滤条件
      filters: {
        name: '',
        teamId: [],
        domainId: [],
        stateFilter: [],
        dataCenterFilter: [],
        osFilter: [],
        businessUnitFilter: [],
        deadlineFilter: [],
        domainTeamTreeValue: null,
        searchType: '1',
        ipAddress: ''
      },
      tableData: [],
      currentPage: 1,
      totalSize: 0,
      pageSize: 10,
      deleteDisabled: true,
      form: {
        datacenter: '',
        name: ''
      },
      multipleSelection: [],
      byteUnit: {
        MB: 1024 * 1024,
        GB: 1024 * 1024 * 1024,
        TB: 1024 * 1024 * 1024 * 1024
      },
      stompClient: '' // 消息推送,
    }
  },
  beforeMount() {
    // this.pagination.size = 10
    if (checkPermission(['SUPER_ADMIN_ROLE'])) {
      this.getVdcDataList()
      this.getBusinessUnitList()
    } else if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
      for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
        this.filters['businessUnitFilter'].push(this.currentRoleOrganizations[i]['organizationTypeId'])
      }
      this.getVdcDataList()
    } else if (checkPermission(['DOMAIN_ADMIN_ROLE'])) {
      for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
        this.filters['domainId'].push(this.currentRoleOrganizations[i]['organizationTypeId'])
        this.getVdcDataListByDomainId(this.currentRoleOrganizations[i]['organizationTypeId'])
      }
    } else if (checkPermission(['TEAM_ADMIN_ROLE', 'TEAM_MEMBER_ROLE'])) {
      for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
        this.filters['teamId'].push(this.currentRoleOrganizations[i]['organizationTypeId'])
      }
    }
  },
  mounted() {
    this.getTableData()
    this.connection()
  },
  beforeDestroy: function() {
    this.disconnect()
  },
  computed: {
    currentUser() {
      return this.$store.getters.user
    },
    currentRoleOrganizations() {
      return this.$store.getters.organizationRoles
    },
    vdcDataListFilter() {
      const filter = []
      const self = this
      for (let i = 0; i < self.vdcDataList.length; i++) {
        filter.push({
          text: self.vdcDataList[i].name,
          value: self.vdcDataList[i].id
        })
      }
      return filter
    }
  },
  methods: {
    checkPermission,
    getVdcDataList() {
      const self = this
      vdcApi.vdcListRequest({
        withDetail: false
      }).then(({ data }) => {
        self.vdcDataList = data
        // this.loadVmList()
      }).catch((error) => {
        console.error(error)
      }).then(() => {
      })
    },
    getBusinessUnitList() {
      const self = this
      businessUnitApi.businessUnitRequest({}).then(({ data }) => {
        self.businessUnitList = data
      }).catch((error) => {
        console.error(error)
      }).then(() => {
      })
    },
    teamFilterCondition() {
      const filter = []
      if (checkPermission(['TEAM_ADMIN_ROLE'])) {
        for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
          filter.push({
            text: this.currentRoleOrganizations[i].name,
            value: this.currentRoleOrganizations[i].organizationTypeId
          })
        }
        return filter
      }
      return filter
    },
    domainFilterCondition() {
      const filter = []
      if (checkPermission(['DOMAIN_ADMIN_ROLE'])) {
        for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
          filter.push({
            text: this.currentRoleOrganizations[i].name,
            value: this.currentRoleOrganizations[i].organizationTypeId
          })
        }
        return filter
      }
      return filter
    },
    formatterBusinessUnit(row, column, cellValue) {
      if (checkPermission(['SUPER_ADMIN_ROLE'])) {
        for (let i = 0; i < this.businessUnitList.length; i++) {
          if (cellValue === this.businessUnitList[i]['id']) {
            return this.businessUnitList[i]['name']
          }
        }
        return cellValue
      } else if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
        for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
          if (cellValue === this.currentRoleOrganizations[i]['organizationTypeId']) {
            return this.currentRoleOrganizations[i]['name']
          }
        }
        return cellValue
      }
      return cellValue
    },
    businessUnitFilterCondition() {
      const filter = []
      if (checkPermission(['SUPER_ADMIN_ROLE'])) {
        for (let i = 0; i < this.businessUnitList.length; i++) {
          filter.push({
            text: this.businessUnitList[i].name,
            value: this.businessUnitList[i].id
          })
        }
        return filter
      } else if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
        for (let i = 0; i < this.currentRoleOrganizations.length; i++) {
          filter.push({
            text: this.currentRoleOrganizations[i].name,
            value: this.currentRoleOrganizations[i].organizationTypeId
          })
        }
        return filter
      }
      return filter
    },
    deliverVMs() {
      const self = this
      this.$refs['deliverForm'].validate((valid) => {
        if (valid) {
          const resourceIds = []
          for (let i = 0; i < self.multipleSelection.length; i++) {
            resourceIds.push(self.multipleSelection[i]['instanceId'])
          }
          const params = {
            unitId: '',
            domainId: '',
            teamId: '',
            description: this.deliverForm['description'],
            deadline: this.deliverForm['deadline'] ? this.dateFormat('yyyy-MM-dd', new Date(this.deliverForm['deadline'])) : '',
            resourceIds: resourceIds
          }
          if (checkPermission(['SUPER_ADMIN_ROLE'])) {
            params['unitId'] = this.deliverForm['businessUnitId']
            params['domainId'] = this.deliverForm['domainId']
            params['teamId'] = this.deliverForm['teamId']
          } else if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
            const domainTreeNodeAndType = this.deliverForm['domainTeamTreeValue'].split('-')
            if (domainTreeNodeAndType.length === 2) {
              if (domainTreeNodeAndType[1] === 'DOMAIN') {
                params['domainId'] = domainTreeNodeAndType[0]
              } else if (domainTreeNodeAndType[1] === 'TEAM') {
                params['teamId'] = domainTreeNodeAndType[0]
              }
            }
          } else if (checkPermission(['DOMAIN_ADMIN_ROLE'])) {
            params['teamId'] = this.deliverForm['teamId']
          } else if (checkPermission(['TEAM_ADMIN_ROLE'])) {
            alert('TODO')
          } else {

          }
          debugger
          pubVmApi.vmDeliverRequest(params).then((data) => {
            self.$message({ message: self.$t('message.deliver_success'), type: 'success' })
            self.handleCloseDeliverDialog()
            self.deliverDialogVisible = false
            self.getTableData()
          }).catch((error) => {
            self.$message({ message: error.msg, type: 'error' })
          })
        } else {
          return false
        }
      })
    },
    handleCloseDeliverDialog(done) {
      const self = this
      self.deliverForm.businessUnitId = ''
      self.deliverForm.deadline = ''
      self.deliverForm.description = ''
      this.$refs['deliverForm'].resetFields()
      if (typeof done === 'function') {
        done()
      }
    },
    getDomainTeam(domainId) {
      const self = this
      const params = {
        domainId: domainId,
        withDetail: false
      }
      domainApi.domainTeamRequest(params).then(({ data }) => {
        self.domainTeamList = data
      }).catch((error) => {
        console.error(error)
      }).then(() => {
      })
    },
    loadDeliverDestinationInfo() {
      if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
        if (Array.isArray(this.multipleSelection) && this.multipleSelection.length > 0) {
          // 如果是运营单位管理员往下级分配多个虚拟机，要求虚拟机的所属运营单位是同一个
          const businessUnitId = this.multipleSelection[0]['resourceUnitId']
          this.getBusinessUnitDomainTeamTree(businessUnitId)
        }
      } else if (checkPermission(['DOMAIN_ADMIN_ROLE'])) {
        const domainId = this.multipleSelection[0]['resourceDomainId']
        this.getDomainTeam(domainId)
      }
    },
    getBusinessUnitDomainTeamTree(businessUnitId) {
      const self = this
      const params = {
        businessUnitId: businessUnitId
      }
      businessUnitApi.businessUnitDomainTeamTreeRequest(params).then(({ data }) => {
        self.businessUnitDomainTree = data
        // 格式转换,后台格式不满足前台treeselect结构的需求
        self.businessUnitDomainTreeFormat = self.cloneDomainTeamTree(data)
      }).catch((error) => {
        console.error(error)
      }).then(() => {
      })
    },
    cloneDomainTeamTree(obj) {
      // typeof [] => 'object', typeof {} => 'object', null,object,array  也是'object'
      if (obj === null || typeof obj !== 'object') {
        return obj
      }
      let copy
      if (obj instanceof Array) {
        copy = []
        for (let i = 0, len = obj.length; i < len; i++) {
          copy.push(this.cloneDomainTeamTree(obj[i]))
        }
      } else {
        copy = {}
        for (const j in obj) {
          // copy[j] = this.clone(obj[j]);
          // source: id name type childDomain
          // target: title value key children
          if (j === 'id') {
            copy['key'] = this.cloneDomainTeamTree(obj['id']) + '-' + this.cloneDomainTeamTree(obj['type'])
            copy['value'] = this.cloneDomainTeamTree(obj['id']) + '-' + this.cloneDomainTeamTree(obj['type'])
          } else if (j === 'name') {
            const domainOrTeamName = obj['type'] === 'DOMAIN' ? this.$t('Vm.resourceDomain') : this.$t('Vm.project')
            copy['title'] = this.cloneDomainTeamTree(obj['name']) + '-' + domainOrTeamName
          } else if (j === 'type') {
            copy['type'] = this.cloneDomainTeamTree(obj['type'])
          } else if (j === 'childDomain') {
            copy['children'] = this.cloneDomainTeamTree(obj['childDomain'])
          }
        }
      }
      return copy
    },
    setDeliverBtnStatus() {
      debugger
      if (this.multipleSelection.length > 0) {
        this.deliverBtnDisabled = false
        this.reclaimBtnDisabled = false
        if (checkPermission(['SUPER_ADMIN_ROLE'])) {
          const businessUnitSet = new Set()
          let businessUnitVMCount = 0
          for (let i = 0; i < this.multipleSelection.length; i++) {
            if (this.multipleSelection[i]['resourceUnitId']) {
              console.log(this.multipleSelection[i]['resourceUnitId'])
              businessUnitSet.add(this.multipleSelection[i]['resourceUnitId'])
              businessUnitVMCount = businessUnitVMCount + 1
            }
          }
          if (businessUnitVMCount !== this.multipleSelection.length) {
            // 如果选中的虚拟机，运营单位都为空（未分配到运营单位），则禁用回收按钮
            this.reclaimBtnDisabled = true
          }
          if (businessUnitSet.size > 0) {
            // 如果选中的虚拟机，存在已分配的虚拟机，则禁用分配按钮
            this.deliverBtnDisabled = true
          }
        } else if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
          const domainSet = new Set()
          let domainVMCount = 0
          const businessUnitSet = new Set()
          for (let i = 0; i < this.multipleSelection.length; i++) {
            if (this.multipleSelection[i]['resourceDomainId']) {
              console.log(this.multipleSelection[i]['resourceUnitId'])
              domainSet.add(this.multipleSelection[i]['resourceDomainId'])
              domainVMCount = domainVMCount + 1
            }
            if (this.multipleSelection[i]['resourceUnitId']) {
              console.log(this.multipleSelection[i]['resourceUnitId'])
              businessUnitSet.add(this.multipleSelection[i]['resourceUnitId'])
            }
          }
          if (domainVMCount !== this.multipleSelection.length) {
            // 如果选中的虚拟机，部门有为空值（未分配到部门）的，则禁用回收按钮
            this.reclaimBtnDisabled = true
          }
          if (domainSet.size > 0 || (domainSet.size === 0 && businessUnitSet.size > 1)) {
            // 如果选中的虚拟机，已分配到部门 或者 未分配但运营单位不一致，则禁用分配按钮
            this.deliverBtnDisabled = true
          }
        } else if (checkPermission(['DOMAIN_ADMIN_ROLE'])) {
          const domainSet = new Set()
          const resourceGroupSet = new Set()
          let resourceGroupVMCount = 0
          for (let i = 0; i < this.multipleSelection.length; i++) {
            if (this.multipleSelection[i]['resourceGroupId']) {
              resourceGroupSet.add(this.multipleSelection[i]['resourceGroupId'])
              resourceGroupVMCount = resourceGroupVMCount + 1
            }
            if (this.multipleSelection[i]['resourceDomainId']) {
              domainSet.add(this.multipleSelection[i]['resourceDomainId'])
            }
          }
          if (resourceGroupVMCount !== this.multipleSelection.length) {
            // 如果选中的虚拟机，项目有为空值的（未分配到项目），则禁用回收按钮
            this.reclaimBtnDisabled = true
          }
          if (resourceGroupSet.size > 0 || (resourceGroupSet.size === 0 && domainSet.size > 1)) {
            // 如果选中的虚拟机，已分配到项目 或者 未分配但是选中的虚拟机所属部门不一致，则禁用分配按钮
            this.deliverBtnDisabled = true
          }
        }
      } else {
        this.deliverBtnDisabled = true
        this.reclaimBtnDisabled = true
      }
    },
    SyncStatus(row) {
      const params = {
        id: row.instanceId,
        regionId: row.regionId,
        platformResourceId: row.platformResourceId,
        dataCenterId: row.dataCenterId
      }
      pubVmApi.SyncStatus({ params: params }).then((data) => {
        this.getTableData()
      }).catch((error) => {
        this.getTableData()
        self.mloading.hide()
        console.error(error)
      }).then(() => {
      })
    },
    startVm(row) {
      this.$confirm('确认进行开机操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.instanceId,
          regionId: row.regionId,
          platformResourceId: row.platformResourceId,
          dataCenterId: row.dataCenterId
        }
        pubVmApi.vmStart({ params: params }).then((data) => {
          this.$message({ type: 'success', message: '启动成功' })
          this.getTableData()
          setTimeout(() => {
            this.SyncStatus()
          }, 5000)
        }).catch((error) => {
          self.mloading.hide()
          this.$message({ type: 'success', message: '启动失败' })
          console.error(error)
        }).then(() => {
        })
      })
    },
    stopVm(row) {
      this.$confirm('确认进行关机操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.instanceId,
          regionId: row.regionId,
          platformResourceId: row.platformResourceId,
          dataCenterId: row.dataCenterId
        }
        pubVmApi.vmStop({ params: params }).then((data) => {
          this.$message({ type: 'success', message: '停止成功' })
          this.getTableData()
          setTimeout(() => {
            this.SyncStatus()
          }, 5000)
        }).catch((error) => {
          self.mloading.hide()
          this.$message({ type: 'success', message: '停止失败' })
          console.error(error)
        }).then(() => {
        })
      })
    },
    restartVm(row) {
      this.$confirm('确认进行重启操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const params = {
          id: row.instanceId,
          regionId: row.regionId,
          platformResourceId: row.platformResourceId,
          dataCenterId: row.dataCenterId
        }
        pubVmApi.vmRestart({ params: params }).then((data) => {
          this.$message({ type: 'success', message: '重启成功' })
          this.getTableData()
          setTimeout(() => {
            this.SyncStatus()
          }, 5000)
        }).catch((error) => {
          self.mloading.hide()
          this.$message({ type: 'success', message: '重启失败' })
          console.error(error)
        }).then(() => {
        })
      })
    },
    showPassword(row) {
      this.$confirm('确认查看云服务器密码操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        pubVmApi.showPassword({
          instanceId: row.instanceId
        }).then((data) => {
          this.password = data.data
          this.passwordDialogVisible = true
          // this.$message({ type: 'success', message: '重启成功' })
          // this.getTableData()
          // setTimeout(() => {
          //   this.SyncStatus()
          // }, 5000)
        }).catch((error) => {
          this.passwordDialogVisible = false
          // self.mloading.hide()
          this.$message.error(error.msg);
          console.error(error)
        }).then(() => {
        })
      })
    },
    checkResourceState(state, data) {
      return data.includes(state)
    },
    openDialog() {
      this.dialogVisible = true
    },
    handleMoreOperationsCommand(cmd) {
      var self = this
      switch (cmd) {
        case 'import':
          self.$router.push({ name: 'importVM', params: { previousPage: 'vmHost', routeLevel: 3 }})
          break
        case 'deliver':
          self.deliverDialogVisible = true
          break
        case 'reclaim':
          self.reclaimVMs()
          break
        case 'multiChange':
          self.multiConfigApplyEvent()
          break
        case 'multiRemove':
          self.multiRemoveApplyEvent()
          break
      }
    },
    reclaimVMs() {
      const self = this
      this.$confirm(this.$t('message.reclaim_confirm'), this.$t('confirm.tip'), {
        confirmButtonText: this.$t('confirm.ok'),
        cancelButtonText: this.$t('confirm.cancel'),
        type: 'warning'
      }).then(() => {
        const resourceIds = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          resourceIds.push(this.multipleSelection[i]['instanceId'])
        }
        const params = {
          type: '', // DOMAIN UNIT ADMIN
          resourceIds: resourceIds
        }
        if (checkPermission(['SUPER_ADMIN_ROLE'])) {
          params['type'] = 'ADMIN'
        } else if (checkPermission(['BUSINESS_UNIT_ADMIN_ROLE'])) {
          params['type'] = 'UNIT'
        } else if (checkPermission(['DOMAIN_ADMIN_ROLE'])) {
          params['type'] = 'DOMAIN'
        }
        pubVmApi.vmReclaimRequest(params).then((data) => {
          self.$message({ message: self.$t('message.reclaim_success'), type: 'success' })
          self.getTableData()
        }).catch((error) => {
          self.$message({ message: error.msg, type: 'error' })
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
      this.setDeliverBtnStatus()
      if (this.multipleSelection.length > 0) {
        this.deleteDisabled = false
      } else {
        this.deleteDisabled = true
      }
    },
    getTableData() {
      const self = this
      self.tableData = []
      self.createDefaultMLoading('#pub')
      self.mloading.show()

      const domainIds = JSON.parse(JSON.stringify(self.filters['domainId']))
      const teamIds = JSON.parse(JSON.stringify(self.filters['teamId']))
      if (this.filters.domainTeamTreeValue != null && this.filters.domainTeamTreeValue != '') {
        const domainTreeNodeAndType = this.filters.domainTeamTreeValue.split('-')
        if (domainTreeNodeAndType.length === 2) {
          if (domainTreeNodeAndType[1] === 'DOMAIN') {
            domainIds.push(domainTreeNodeAndType[0])
          } else if (domainTreeNodeAndType[1] === 'TEAM') {
            teamIds.push(domainTreeNodeAndType[0])
          }
        }
      }

      pubVmApi.getVmList({
        pageNumber: self.currentPage,
        pageSize: self.pageSize,
        name: self.filters.name,
        ip: self.filters.ipAddress,
        teamIds: teamIds,
        dataCenterId: self.filters['dataCenterFilter'].join(),
        businessUnitIds: self.filters['businessUnitFilter'],
        domainIds: domainIds
      }).then((data) => {
        self.tableData = data.data.pageData
        self.totalSize = data.data.total
        self.mloading.hide()
      }).catch((error) => {
        self.mloading.hide()
        console.log(error)
      })
    },
    cerateVm() {
      this.$router.push({ name: 'createPubVm', params: { previousPage: 'vmList', routeLevel: 3 } })
    },
    clickDelete() {
      const self = this
      this.$confirm(this.$t('confirm.delete_confirm'), this.$t('confirm.tip'), {
        confirmButtonText: this.$t('btn.ok'),
        cancelButtonText: this.$t('btn.cancel'),
        type: 'warning'
      }).then(() => {
        self.mloading.show()
        const vmIds = []
        let isLocal = true
        switch (self.deleteType) {
          case 'local':
            isLocal = true
            break
          case 'cloud':
            isLocal = false
            break
          default:
            break
        }
        for (let i = 0; i < self.multipleSelection.length; i++) {
          vmIds.push(self.multipleSelection[i]['instanceId'])
        }
        const params = {
          ids: vmIds,
          local: isLocal
        }
        pubVmApi.vmDeleteRequest({
          params: params
        }).then(() => {
          this.dialogVisible = false
          this.$message({ type: 'success', message: this.$t('confirm.delete_success') })
          self.mloading.hide()
          this.getTableData()
        }).catch((error) => {
          this.$message({ type: 'error', message: error.msg })
          this.dialogVisible = false
          self.mloading.hide()
        })
      })
    },
    importVM() {
      this.$router.push({ name: 'importPubVm', params: { previousPage: 'vmList', routeLevel: 3 } })
    },
    edit(index, row) {
      this.$router.push({
        name: 'vmListEdit',
        params: { previousPage: 'editvmList', isAdd: false, id: row.instanceId, routeLevel: 3, type: row.type }
      })
    },
    changeSearchType() {
      if (this.filters.searchType === '1') {
        this.filters.ipAddress = ''
      } else if (this.filters.searchType === '2') {
        this.filters.name = ''
      }
    },
    clickSearch() {
      this.resetFilterTable()
      this.getTableData()
    },
    resetFilterTable() {
      // 重置页面信息，触发重新加载操作
      this.currentPage = 1
      this.totalSize = 0
      this.pageSize = 10
      this.table.data = []
    },
    getStateIcon(state, stateName) {
      return pubVmUtil.getVmStateHtml(state, stateName)
    },
    connection() {
      const self = this
      messageApi.getMessageUrlRequest().then(({data}) => {
        const socket = new SockJS(data)// 获取STOMP子协议的客户端对象
        this.stompClient = Stomp.over(socket) // 建立连接对象
        const headers = {Authorization: ''}// 定义客户端的认证信息,按需求配置
        // 向服务器发起websocket连接
        this.stompClient.connect(headers, () => {
          const username = self.currentUser['username']
          this.stompClient.subscribe('/topic/PUB_VM/' + username, (msg) => { // 订阅服务端提供的某个topic
            this.webSocketMsg(msg)
          }, headers)
        }, (err) => {
          console.log(err)
        })
      }).catch((error) => {
        console.log(error)
      })
    },
    disconnect() {
      // 断开连接
      if (this.stompClient) {
        this.stompClient.disconnect()
      }
    },
    webSocketMsg(msg) {
      const self = this
      const info = JSON.parse(msg.body)
      if (info['eventResult'] === 'SUCCESS') {
        this.$notify({
          title: self.$t('message.success'),
          dangerouslyUseHTMLString: true,
          message: info.eventContent['msgLocal'],
          type: 'success'
        })
        self.getTableData()
      } else {
        this.$notify({
          title: self.$t('message.failed'),
          dangerouslyUseHTMLString: true,
          message: info.eventContent['msgLocal'],
          type: 'error'
        })
      }
    },
  }
}
</script>

